/**
 Rabbit 2013-3-3
 chart 组件采用统一配置创建，就是说使用者无需关心 chart 的样式及生成方式
 只需提供数据源、简单的配置信息（轴类型，字段等）

 1.样式边距颜色等更多配置采用配置文件方式加入
 2.所有属性采用hchart内部属性，便于修改
 3.同时提供接口于开发人员对chart的任意修改
 4.chart组件对流量、数量的中文、英文单位的处理
 5.chart组件对实时数据的处理

 线图数据轴注意几点：
 1.Y轴有数据为百分数时，最大值为100
 2.Y轴有小数时，保留几位
 3.Y轴单位为整数时，不能出现小数

 注意：
 1.chart 容器DIV大小发生改变时，需重绘（不能重复创建对象）
 2.其它情况用chart函数 validateNow，validateData
 3.客户端不在做数据排序（数据排序由后台处理）
 4.柱状图如果不是多序列则需要根据chartData 从新计算 categories
 */
/*
function HSChartModel() {
// zone, interface, app, user ...
this.target = null;
// traffic, bw, session, count
this.dataType = null;
// current, hour, day, month
this.period = null;

}
*/

/**
 * HChart themes
 */
Highcharts.theme = {
	colors: ['#ff7013', '#00CC33','#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'],
	
	chart : {
		className : 'skies',
		borderWidth : 0,
		//plotShadow: true,
		//plotBackgroundImage: '/demo/gfx/skies.jpg',
		/*plotBackgroundColor: {
		 linearGradient: [0, 0, 250, 500],
		 stops: [
		 [0, 'rgba(255, 255, 255, 1)'],
		 [1, 'rgba(255, 255, 255, 0)']
		 ]
		 },*/
		plotBorderWidth : 0
	},
	title : {
		style : {
			color : '#3E576F',
			font : '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	subtitle : {
		style : {
			color : '#6D869F',
			font : '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
		}
	},
	xAxis : {
		gridLineWidth : 0,
		lineColor : '#C0D0E0',
		tickColor : '#C0D0E0',
		labels : {
			style : {
				color : '#666',
				fontSize : '12px',
				fontWeight : 'normal'//'bold'
			}
		},
		title : {
			style : {
				color : '#666',
				font : '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	yAxis : {
		alternateGridColor : 'rgba(255, 255, 255, .5)',
		lineColor : '#C0D0E0',
		tickColor : '#C0D0E0',
		tickWidth : 1,
		lineWidth : 1,
		labels : {
			style : {
				color : '#666',
				fontSize : '12px',
				fontWeight : 'normal'//'bold'
			}
		},
		title : {
			style : {
				color : '#666',
				font : '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif'
			}
		}
	},
	legend : {
		itemStyle : {
			font : '9pt Trebuchet MS, Verdana, sans-serif',
			color : '#3E576F'
		},
		itemHoverStyle : {
			color : 'black'
		},
		itemHiddenStyle : {
			color : 'silver'
		}
	},
	labels : {
		style : {
			color : '#3E576F'
		}
	}
};

// Apply the theme
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);

// Ext.namespace('webapp.common');
/**
 * Rabbit
 * HChart Class
 */
var HChart = function(chartStruct, chartData) {
	var _that = this;
	var _chartObj = null;

	var _chartStruct = chartStruct ? chartStruct : null;
	var _chartData = chartData ? chartData : null;

	var _chartContainerView = {
		width : null,
		height : null
	};

	var colors = Highcharts.getOptions().colors;

	this.setTitle = function(title, subtitle) {
		if(_chartObj) {
			alert(1)
			_chartObj.setTitle({title:'xxx'});
			_chartObj.redraw();
		}
	}
	
	this.setSize = function(adjWidth, adjHeight) {
		if(_chartObj) {
			_chartObj.setSize(adjWidth, adjHeight);
		}
	}
	this.redraw = function() {
		if(_chartObj) {
			_chartObj.redraw();
		}
	}
	
	this.getChartObj = function() {
		return _chartObj;
	}
	
	this.ChartUnit = HChartUtil.ChartUnit;

	/**
	 * 得到图表基本参数对象
	 */
	var _getInitChart = function(chartStruct) {
		return {
			renderTo : chartStruct.renderTo,
			type : chartStruct.chartType,
			borderWidth : 0,
			plotShadow : false,
			plotBorderWidth : null,
			plotBackgroundColor : null,

			marginTop : chartStruct.marginTop,
			marginRight : chartStruct.marginRight,
			marginBottom : chartStruct.marginBottom,
			marginLeft : chartStruct.marginLeft
		}
	}
	var _getInitTitle = function(chartStruct) {
		return {
			text : chartStruct.title
		}
	}
	var _getInitSubTitle = function(chartStruct) {
		return {
			text : chartStruct.subtitle
		}
	}
	/**
	 * 得到图表X轴对象
	 */
	var _getInitXAxis = function(chartStruct) {
		var xAxisCfg = {};
		if(chartStruct.xAxisType == 'linear') {
			xAxisCfg.categories = chartStruct.categories;
		} else {
			xAxisCfg.type = 'datetime';
			xAxisCfg.tickPixelInterval = 150;
			//150px画一个x刻度
			xAxisCfg.dateTimeLabelFormats = chartStruct.dateTimeLabelFormats;
		}
		
		xAxisCfg.labels = {
			style : {
				fontSize : '12px',
				fontAlign : 'center',
				fontFamily : 'Verdana, sans-serif'
			},
			step:chartStruct.xAxisLabelsStep? chartStruct.xAxisLabelsStep:1
			//不在此处理categories 单序列问题
			/*,formatter:function() {
			 if(this.chart.options.xAxis['categories'] && this.chart.options.xAxis.categories.length == 0 ||
			 this.chart.options.xAxis['type'] && this.chart.options.xAxis.type != 'datetime') {
			 var categorieName = this.chart.options.series[0].data[this.value].name;
			 return categorieName;
			 } else {
			 debugger;
			 return this.value;
			 }
			 }*/
		}
		if(chartStruct.xAxisLabelsRotation != 0) {
			xAxisCfg.labels.rotation = chartStruct.xAxisLabelsRotation;
			//-45,
			xAxisCfg.labels.align = 'right';
		}

		return xAxisCfg;
	}
	/**
	 * 得到图表Y轴对象
	 */
	var _getInitYAxis = function(chartStruct) {
		var yAxisCfg = {};
		if(chartStruct.yAxisTitle != '') {
			yAxisCfg.title = {
				text : chartStruct.yAxisTitle
			}
		} else {
			yAxisCfg.title = {
				text : ''
			}
		}
		if(chartStruct.unit != '') {
			yAxisCfg.labels = {
				formatter : function() {
					return this.value + chartStruct.unit;
				}
			}
		}
		if(chartStruct.yAxisMin != null)
			yAxisCfg.min = chartStruct.yAxisMin;
		if(chartStruct.yAxisMax != null)
			yAxisCfg.max = chartStruct.yAxisMax;
		if(yAxisCfg.min > yAxisCfg.max)
			delete yAxisCfg.min;

		if(chartStruct.yAxisAllowDecimals)
			yAxisCfg.allowDecimals = true;
		else
			yAxisCfg.allowDecimals = false;

		yAxisCfg.tickPixelInterval = 50;
		//50px画一个y刻度

		return yAxisCfg;
	}
	/**
	 * 导出
	 */
	var _getInitExporting = function(chartStruct) {
		var exportingCfg = {};
		if(chartStruct.enabledExporting)
			exportingCfg.enabled = true;
		else
			exportingCfg.enabled = false;

		return exportingCfg;
	}
	/**
	 * 得到图标图例对象
	 */
	var _getInitLegend = function(chartStruct) {
		var legendCfg = {};
		if(chartStruct.enabledLegend) {
			legendCfg.enabled = true;

			if(chartStruct.legend) {
				legendCfg = chartStruct.legend;
			} else {
				legendCfg.backgroundColor = '#FFFFFF';
				legendCfg.reversed = true;
				legendCfg.shadow = true;
			}
		} else {
			legendCfg.enabled = false;
		}
		return legendCfg;
	}
	/**************************************LineChart begin*****************************************/
	var _adjustLineChartData = function(chartData) {
		var scale = _that.ChartUnit.getScale();
		// debugger;
		if(Object.prototype.toString.apply(chartData) === '[object Array]') {
			for(var l=0; l<chartData.length; l++) {
				var dataList = chartData[l].data;
				if(Object.prototype.toString.apply(dataList) === '[object Array]') {
					for(var i = 0; i < dataList.length; i++) {
						if(Object.prototype.toString.apply(dataList[i]) === '[object Array]') {
							dataList[i][1] = parseFloat((dataList[i][1] / scale).toFixed(2));
						} else {
							dataList[i] = parseFloat((dataList[i] / scale).toFixed(2));
						}
					}
				}
			}
		}
		return chartData;
	}
	/**
	 * 得到线图数据点参数对象
	 */
	var _getInitLineChartPlotOptions = function(chartStruct) {
		var plotOptionsCfg = {};
		plotOptionsCfg.line = {
			dataLabels : {
				enabled : chartStruct.enabledDataLabels ? true : false
			},
			marker : {
				enabled : false,
				states : {
					hover : {
						enabled : true,
						symbol : 'circle',
						radius : 4,
						lineWidth : 1
					}
				}
			},
			enableMouseTracking : true
		}
		return plotOptionsCfg;
	}
	/**
	 * 得到数据点提示框对象
	 */
	var _getInitLineChartTooltip = function(chartStruct) {
		var tooltipCfg = {};
		if(chartStruct.enabledTooltip) {
			tooltipCfg.enabled = true;

			if(chartStruct.tooltipFormatter && jQuery.isFunction(chartStruct.tooltipFormatter)) {
				tooltipCfg.formatter = chartStruct.tooltipFormatter;
			} else {
				tooltipCfg.formatter = function() {
					return '<b>' + this.series.name + '</b><br/>' +this.point.category+'<br/>'+'<b>'+this.point.y+'</b>'+chartStruct.unit;
					//return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + ': ' + this.y + chartStruct.unit;

					//maincontentText: '值：' + this.y +':<br/>时间：'+ Highcharts.dateFormat('%Y-%m-%e %H:%M:%S', this.x),
				}
			}
		} else {
			tooltipCfg.enabled = false;
		}

		return tooltipCfg;
	}
	/**
	 * 得到图标数据序列对象 TODO
	 */
	var _getInitLineChartSeries = function(chartStruct, chartData) {
		chartData = _adjustLineChartData(chartData);
		return chartData;
	}
	/**
	 * 创建线图
	 */
	var _createLineChart = function() {
		if(_chartObj == null && _chartStruct) {

			var chartCfg = {
				reflow : true, //跟随容器大小改变

				chart : _getInitChart(_chartStruct),
				title : _getInitTitle(_chartStruct),
				subtitle : _getInitSubTitle(_chartStruct),
				xAxis : _getInitXAxis(_chartStruct),
				yAxis : _getInitYAxis(_chartStruct),
				plotOptions : _getInitLineChartPlotOptions(_chartStruct),
				tooltip : _getInitLineChartTooltip(_chartStruct),
				series : _getInitLineChartSeries(_chartStruct, _chartData),
				exporting : _getInitExporting(_chartStruct),
				legend : _getInitLegend(_chartStruct)
			}
			_chartObj = new Highcharts.Chart(chartCfg);

		}
	}
	/**************************************LineChart end*****************************************/

	/**************************************AreaChart begin*****************************************/
	/**
	 * 调整区域图数据
	 * 需要考虑多序列
	 */
	var _adjustAreaChartData = function(chartData) {
		var scale = _that.ChartUnit.getScale();
		// debugger;
		if(Object.prototype.toString.apply(chartData) === '[object Array]') {
			for(var l=0; l<chartData.length; l++) {
				var dataList = chartData[l].data;
				if(Object.prototype.toString.apply(dataList) === '[object Array]') {
					for(var i = 0; i < dataList.length; i++) {
						if(Object.prototype.toString.apply(dataList[i]) === '[object Array]') {
							dataList[i][1] = parseFloat((dataList[i][1] / scale).toFixed(2));
						} else {
							dataList[i] = parseFloat((dataList[i] / scale).toFixed(2));
						}
					}
				}
			}
		}
		return chartData;
	}
	/**
	 * 得到线图数据点参数对象
	 */
	var _getInitAreaChartPlotOptions = function(chartStruct) {
		var plotOptionsCfg = {};
		plotOptionsCfg.area = {
			dataLabels : {
				enabled : chartStruct.enabledDataLabels ? true : false
			},
			//fillOpacity : 0.5,
			// threshold: null,
			fillColor: {
                linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
                stops: [
                    [0, Highcharts.getOptions().colors[0]],
                    [1, 'rgba(255,255,255,255)']
                ]
            },
			lineWidth: 1,
			marker : {
				enabled : false,
				states : {
					hover : {
						enabled : true,
						symbol : 'circle',
						radius : 4
						// ,lineWidth : 1
					}
				}
			},
			shadow: false,
            states: {
                hover: {
                    lineWidth: 1
                }
            },
			enableMouseTracking : true
		}
		return plotOptionsCfg;
	}
	/**
	 * 得到数据点提示框对象
	 */
	var _getInitAreaChartTooltip = function(chartStruct) {
		var tooltipCfg = {};
		if(chartStruct.enabledTooltip) {
			tooltipCfg.enabled = true;

			if(chartStruct.tooltipFormatter && jQuery.isFunction(chartStruct.tooltipFormatter)) {
				tooltipCfg.formatter = chartStruct.tooltipFormatter;
			} else {
				tooltipCfg.formatter = function() {
					return '<b>' + this.series.name + '</b><br/>' +this.point.category+'<br/>'+'<b>'+this.point.y+'</b>'+chartStruct.unit;//+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + ': ' + this.y + chartStruct.unit;

					//maincontentText: '值：' + this.y +':<br/>时间：'+ Highcharts.dateFormat('%Y-%m-%e %H:%M:%S', this.x),
				}
			}
		} else {
			tooltipCfg.enabled = false;
		}

		return tooltipCfg;
	}
	/**
	 * 得到图标数据序列对象 TODO
	 */
	var _getInitAreaChartSeries = function(chartStruct, chartData) {
		chartData = _adjustAreaChartData(chartData);
		return chartData;
	}
	/**
	 * 创建线图
	 */
	var _createAreaChart = function() {
		if(_chartObj == null && _chartStruct) {

			var chartCfg = {
				reflow : true, //跟随容器大小改变

				chart : _getInitChart(_chartStruct),
				title : _getInitTitle(_chartStruct),
				subtitle : _getInitSubTitle(_chartStruct),
				xAxis : _getInitXAxis(_chartStruct),
				yAxis : _getInitYAxis(_chartStruct),
				plotOptions : _getInitAreaChartPlotOptions(_chartStruct),
				tooltip : _getInitAreaChartTooltip(_chartStruct),
				series : _getInitAreaChartSeries(_chartStruct, _chartData),
				exporting : _getInitExporting(_chartStruct),
				legend : _getInitLegend(_chartStruct)
			}
			_chartObj = new Highcharts.Chart(chartCfg);

		}
	}
	/**************************************AreaChart end*****************************************/

	/**************************************ColumnChart begin*****************************************/

	/**
	 * 调整数据
	 */
	var _adjustColumnChartData = function(chartData) {
		/*var _colors = Highcharts.getOptions().colors;

		if(Object.prototype.toString.apply(chartData) === '[object Array]') {
			for(var i = 0; i < chartData.length; i++) {
				chartData[i].color = _colors[i];
			}
		}*/
		var scale = _that.ChartUnit.getScale();
		// debugger;
		
		if(Object.prototype.toString.apply(chartData) === '[object Array]') {
			for(var l=0; l<chartData.length; l++) {
				var dataList = chartData[l].data;
				if(Object.prototype.toString.apply(dataList) === '[object Array]') {
					for(var i = 0; i < dataList.length; i++) {
						dataList[i].y = parseFloat((dataList[i].y / scale).toFixed(2));
					}
				}
			}
		}
		
		return chartData;
	}
	/**
	 * 得到柱状图数据点参数对象
	 */
	var _getInitColumnChartPlotOptions = function(chartStruct) {
		var plotOptionsCfg = {
			column : {
				cursor : 'pointer',
				point : {
					events : {
						click : function() {
							if(jQuery.isFunction(chartStruct.columnClickHandle)) {
								chartStruct.columnClickHandle(this);
							}
							/*alert('click')
							 var drilldown = this.drilldown;
							 if (drilldown) { // drill down
							 setChart(drilldown.name, drilldown.categories, drilldown.data, drilldown.color);
							 } else { // restore
							 setChart(name, categories, data);
							 }*/
						}
					}
				}
			}
		}

		if(chartStruct.enabledDataLabels) {
			plotOptionsCfg.column.dataLabels = {
				enabled : true,
				color : '#666',
				style : {
					fontSize : 11,
					fontWeight : 'normal'
				},
				formatter : function() {
					return this.y + chartStruct.unit;
				}
			}
		} else {
			plotOptionsCfg.column.dataLabels = {
				enabled : false
			}
		}
		return plotOptionsCfg;
	}
	/**
	 * 得到数据点提示框对象
	 */
	var _getInitColumnChartTooltip = function(chartStruct) {
		var tooltipCfg = {};
		if(chartStruct.enabledTooltip) {
			tooltipCfg.enabled = true;

			if(chartStruct.tooltipFormatter && jQuery.isFunction(chartStruct.tooltipFormatter)) {
				tooltipCfg.formatter = chartStruct.tooltipFormatter;
			} else {
				tooltipCfg.formatter = function() {
					var point = this.point, s = this.x + ':<b>' + this.y + chartStruct.unit + '</b><br/>';
					if(point.drilldown) {
						s += '点击 "' + point.category + '" 可查看趋势信息';
					} 
					return s;

					//maincontentText: '值：' + this.y +':<br/>时间：'+ Highcharts.dateFormat('%Y-%m-%e %H:%M:%S', this.x),
				}
			}
		} else {
			tooltipCfg.enabled = false;
		}

		return tooltipCfg;
	}
	/**
	 * 得到图标数据序列对象 TODO
	 */
	var _getInitColumnChartSeries = function(chartStruct, chartData) {
		chartData = _adjustColumnChartData(chartData);
		return chartData;
	}
	/**
	 * 创建柱状图
	 */
	var _createColumnChart = function() {
		if(_chartObj == null && _chartStruct) {

			var chartCfg = {
				reflow : true, //跟随容器大小改变

				chart : _getInitChart(_chartStruct),
				title : _getInitTitle(_chartStruct),
				subtitle : _getInitSubTitle(_chartStruct),
				xAxis : _getInitXAxis(_chartStruct),
				yAxis : _getInitYAxis(_chartStruct),
				plotOptions : _getInitColumnChartPlotOptions(_chartStruct),
				tooltip : _getInitColumnChartTooltip(_chartStruct),
				series : _getInitColumnChartSeries(_chartStruct, _chartData),
				exporting : _getInitExporting(_chartStruct),
				legend : _getInitLegend(_chartStruct)
			}
			_chartObj = new Highcharts.Chart(chartCfg);

		}
	}
	/**************************************ColumnChart end*****************************************/

	/**************************************PieChart begin*****************************************/
	var _adjustPieChartData = function(chartData) {
		/*var scale = _that.ChartUnit.getScale();
		// debugger;
		var dataList = chartData[0].data;
		if(Object.prototype.toString.apply(dataList) === '[object Array]') {
			for(var i = 0; i < dataList.length; i++) {
				dataList[i].y = parseFloat((dataList[i].y / scale).toFixed(2));
			}
		}
		return chartData;*/
	}
	/**
	 * 得到线图数据点参数对象
	 */
	var _getInitPieChartPlotOptions = function(chartStruct) {
		var plotOptionsCfg = {};
		plotOptionsCfg.pie = {
			allowPointSelect : true,
			cursor : 'pointer',
			dataLabels : {
				enabled : true,
				color : '#000000',
				connectorColor : '#000000',

				formatter : function() {
					var pointName = this.point.name;
					//var pointValue = this.point.y;
					var valuePercentage = this.percentage;
					return '<b>' + pointName + '</b>: ' + valuePercentage.toFixed(2) + ' %';
				}
			},
			showInLegend : chartStruct.enabledLegend ? true : false
		}
		return plotOptionsCfg;
	}
	/**
	 * 得到数据点提示框对象
	 */
	var _getInitPieChartTooltip = function(chartStruct) {
		var tooltipCfg = {};
		if(chartStruct.enabledTooltip) {
			tooltipCfg.enabled = true;

			if(chartStruct.pointFormat && jQuery.isFunction(chartStruct.pointFormat)) {
				tooltipCfg.pointFormat = chartStruct.pointFormat;
			} else {
				tooltipCfg.pointFormat = '{series.name} {point.y} : <b>{point.percentage}%</b>';
			}
			tooltipCfg.percentageDecimals = 2;
		} else {
			tooltipCfg.enabled = false;
		}

		return tooltipCfg;
	}
	/**
	 * 得到图标数据序列对象 TODO
	 */
	var _getInitPieChartSeries = function(chartStruct, chartData) {
		//_adjustPieChartData(chartData);
		return chartData;
	}
	/**
	 * 创建线图
	 */
	var _createPieChart = function() {
		if(_chartObj == null && _chartStruct) {

			var chartCfg = {
				reflow : true, //跟随容器大小改变

				chart : _getInitChart(_chartStruct),
				title : _getInitTitle(_chartStruct),
				subtitle : _getInitSubTitle(_chartStruct),
				plotOptions : _getInitPieChartPlotOptions(_chartStruct),
				tooltip : _getInitPieChartTooltip(_chartStruct),
				series : _getInitPieChartSeries(_chartStruct, _chartData),
				exporting : _getInitExporting(_chartStruct),
				legend : _getInitLegend(_chartStruct)
			}
			_chartObj = new Highcharts.Chart(chartCfg);

		}
	}
	/**************************************PieChart end*****************************************/

	/**
	 * 初始化Chart对象  TODO
	 */
	var _initChart = function() {
		if(_chartStruct) {
			//计算单位
			_that.ChartUnit.initScale(_chartData, _chartStruct.displayDataType, 'zh-cn');
			
			_chartStruct.unit = HChartUtil.ChartUnit.getUnit();
			// debugger;
			
			switch(_chartStruct.chartType) {
				case 'line':
				case 'lineChart':
					_createLineChart();
					break;
				case 'area':
				case 'areaChart':
					_createAreaChart();
					break;
				case 'column':
				case 'columnChart':
					_createColumnChart();
					break;
				case 'pie':
				case 'pieChart':
					_createPieChart();
					break;
				default:
					// throw {name:'HSChart', message:'HSChart ChartStruct chartType Error(ResourceManage RN:145)'};
					break;
			}
		}
	}
	_initChart();
}



/**
HChart Error : 

String value sent to series.data, expected Number

This happens if you pass in a string as a data point, for example in a setup like this:

series: [{
	data: ["3", "5", "1", "6"]
}]
Highcharts expects the data values to be numbers. The most common reason for this is that data is parsed from CSV or from a XML source, and the implementer forgot to run parseFloat on the parsed value.

For performance reasons internal type casting is not performed, and only the first value is checked (since 2.3).
*/
